﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Runtime;
using System.Xml;
using BPM.Base.Tools;
using BPM.Foundation.WFDB;
using System.Workflow.Activities;
using System.IO;
using System.Data;
using BPM.Base.DataTypeLib;
namespace BPM.Foundation.WFService
{
    public partial interface IWorkflowService
    {
        [System.ServiceModel.OperationContract]
        Guid createWorkflow(string pid, WorkflowStartParameter parameter);

        [System.ServiceModel.OperationContract]
        int? businessSubmit(string pid, SubmitResult submitResult);

        [System.ServiceModel.OperationContract]
        int? setStateTransactUser(string pid, Guid instanceID, Guid stateInstanceID, string transactUser, string type, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description);
        
        [System.ServiceModel.OperationContract]
        int? refurbishTimelimit(string pid);

        [System.ServiceModel.OperationContract]
        int? timelimitTransact(string pid);

        [System.ServiceModel.OperationContract]
        int? regulateProcess(string pid,WF_Instance wf_instance);

        [System.ServiceModel.OperationContract]
        int? regulateState(string pid, WF_InstanceState wf_instanceState);

        [System.ServiceModel.OperationContract]
        List<string> getStateList(string pid, Guid instanceID);

        [System.ServiceModel.OperationContract]
        int? gotoState(string pid, Guid instanceID, string stateName, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description);

        [System.ServiceModel.OperationContract]
        int? statePostpone(string pid, Guid instanceID, Guid stateInstanceID, int postponeValue, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description);
        
        [System.ServiceModel.OperationContract]
        int? processFreeze(string pid, Guid instanceID, int freeze, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description);
       
        [System.ServiceModel.OperationContract]
        InstanceTree getProcessTree(string pid, Guid instanceID);
    }
    public partial class WorkflowService : IWorkflowService
    {
        //[6.1	从XOML字串创创建工作流(内部方法)]
        private WorkflowInstance CreateWorkflowFormXomlString(string xomlstring, string rulesstring, Dictionary<string, object> list,Guid instanceID)
        {

            if(instanceID==Guid.Empty)
            {
                instanceID = Guid.NewGuid();
            }
            try
            {
                System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();

                byte[] a = utf8.GetBytes(rulesstring);

                System.IO.MemoryStream m1 = new System.IO.MemoryStream(a);

                XmlReader rules = XmlReader.Create(m1);

                byte[] b = utf8.GetBytes(xomlstring);

                System.IO.MemoryStream m2 = new System.IO.MemoryStream(b);

                XmlReader xoml = XmlReader.Create(m2);

                System.Workflow.Runtime.WorkflowInstance instance;

                instance = runtime.CreateWorkflow(xoml, rules, list, instanceID);

                instance.Start();

                return instance;
            }
            catch (System.Workflow.ComponentModel.Compiler.WorkflowValidationFailedException ex)
            {
                MyLog.writeError("创建流程实例时出错:" + ex.Message);

                return null;
            }
        }

        //[6.2	创建流程]
        public Guid createWorkflow(string pid, WorkflowStartParameter parameter)
        {
            //[0]
            System.Threading.Thread.Sleep(1000);

            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                if ( wfDB.WF_Instance.Count(p => p.instanceID == parameter.instanceID) != 0)
                {
                    return Guid.Empty;
                }
                if(parameter.nextStateUserNo=="none")
                {
                    parameter.nextStateUserNo = "";
                }
                Dictionary<string, object> list = new Dictionary<string, object>();


                //[1]
                if (parameter == null)
                    return Guid.Empty;

                //[2]
                var wfTemplate = this.getWFTemplate("", parameter.templateID, parameter.templateEdition);
                if (wfTemplate == null)
                {
                    return Guid.Empty;
                }

                #region  [3][parameter.businessParameter]

                //[3]
                if (parameter.businessParameter == null || parameter.businessParameter.businessType == null
                    || parameter.businessParameter.businessID == null || parameter.businessParameter.masterBusinessID == null
                    || parameter.businessParameter.businessName == null || parameter.businessParameter.businessDescription == null
                    || parameter.businessParameter.urgency == null || parameter.businessParameter.secrecy == null
                    || string.IsNullOrEmpty(parameter.businessParameter.startUser) || string.IsNullOrEmpty(parameter.businessParameter.startDepartment)
                    || string.IsNullOrEmpty(parameter.businessParameter.startDuty) || parameter.businessParameter.startTime == null)
                    return Guid.Empty;
                else
                {
                    list.Add("业务类型", parameter.businessParameter.businessType);
                    list.Add("业务编号", parameter.businessParameter.businessID);
                    list.Add("主业务编号", parameter.businessParameter.masterBusinessID);
                    list.Add("业务名称", parameter.businessParameter.businessName);
                    list.Add("业务描述", parameter.businessParameter.businessDescription);
                    list.Add("业务紧急度", parameter.businessParameter.urgency);
                    list.Add("业务保密度", parameter.businessParameter.secrecy);
                    list.Add("启动人员", parameter.businessParameter.startUser);
                    list.Add("启动部门", parameter.businessParameter.startDepartment);
                    list.Add("启动职能", parameter.businessParameter.startDuty);
                    list.Add("启动时间", DateTime.Now);
                    list.Add("测试编号", parameter.businessParameter.testID);
                }
                #endregion  [3][parameter.businessParameter]


                #region [4][parameter.childWorkflowParameter]
                //[4]
                if (parameter.childWorkflowParameter != null)
                {
                    if (parameter.childWorkflowParameter.masterInstanceID == null
                        || parameter.childWorkflowParameter.regressGroup == null)
                    {
                        return Guid.Empty;
                    }
                    else
                    {
                        list.Add("流程回归组", parameter.childWorkflowParameter.regressGroup);
                        list.Add("回归主流程", parameter.childWorkflowParameter.regress);
                        list.Add("主流程编号", parameter.childWorkflowParameter.masterInstanceID);
                    }
                }
                #endregion [4][parameter.ChildWorkflowParameter]


                #region [5][parameter.powerParameter]
                //[5]
                if (parameter.powerParameter != null)
                {
                    if (parameter.powerParameter.manageDepartment == null || parameter.powerParameter.manageDuty == null
                        || parameter.powerParameter.manageUser == null || parameter.powerParameter.seeDepartment == null
                        || parameter.powerParameter.seeDuty == null || parameter.powerParameter.seeUser == null
                        || parameter.powerParameter.startUserPower == null
                        || parameter.powerParameter.overtimeOperate == null
                        )
                        return Guid.Empty;
                    else
                    {
                        if (parameter.powerParameter.manageDepartment != "none")
                            list.Add("管理部门", parameter.powerParameter.manageDepartment);

                        if (parameter.powerParameter.manageDuty != "none")
                            list.Add("管理职能", parameter.powerParameter.manageDuty);

                        if (parameter.powerParameter.manageUser != "none")
                            list.Add("管理人员", parameter.powerParameter.manageUser);

                        if (parameter.powerParameter.seeDepartment != "none")
                            list.Add("查看部门", parameter.powerParameter.seeDepartment);

                        if (parameter.powerParameter.seeDuty != "none")
                            list.Add("查看职能", parameter.powerParameter.seeDuty);

                        if (parameter.powerParameter.seeUser != "none")
                            list.Add("查看人员", parameter.powerParameter.seeUser);

                        if (parameter.powerParameter.startUserPower != "none")
                            list.Add("启动人员特殊权限", parameter.powerParameter.startUserPower);

                        if (parameter.powerParameter.transactTimelimit != -1)
                            list.Add("办理时限", parameter.powerParameter.transactTimelimit);

                        if (parameter.powerParameter.overtimeOperate != "none")
                            list.Add("超时操作", parameter.powerParameter.overtimeOperate);
                    }
                }
                #endregion [5][parameter.powerParameter]
                
                #region [6][parameter.dataForm]
                //[6]
                //暂时不考虑
                if (parameter.dataForm != null)
                {
                    if (parameter.dataForm.childWorkflowTab != null)
                    {

                        foreach (DataForm.childWorkflowTabRow cRow in parameter.dataForm.childWorkflowTab.Rows)
                        {
                            if (cRow.IsinstanceIDNull())
                            {
                                cRow.instanceID = Guid.Empty;
                            }
                        }
                    }
                    string xml = this.convertDataSetToString(parameter.dataForm);
                    list.Add("数据表单", xml);
                }
                #endregion [6][parameter.dataForm]



                #region [7][parameter.nextStateUserNo]
                //[7]
                if (!string.IsNullOrEmpty(parameter.nextStateUserNo) && parameter.nextStateUserNo != "none")
                    list.Add("下一状态办理人员", parameter.nextStateUserNo);
                #endregion [7][parameter.nextStateUserNo]

                if (!string.IsNullOrEmpty(parameter.nextStateInceptDept) && parameter.nextStateInceptDept != "none")
                    list.Add("下一状态接件部门", parameter.nextStateInceptDept);

                if (!string.IsNullOrEmpty(parameter.nextStateInceptDuty) && parameter.nextStateInceptDuty != "none")
                    list.Add("下一状态接件职能", parameter.nextStateInceptDuty);

                #region [8][CreateWorkflowFormXomlString]
                //[8]
                WorkflowInstance instance = CreateWorkflowFormXomlString(wfTemplate.templateData, wfTemplate.templateRules, list, parameter.instanceID);
                #endregion [8][CreateWorkflowFormXomlString]


                #region [9][return instance.InstanceId]
                //[9]
                if (instance == null)
                {
                    MyLog.writeError("创建流程时出现错误，参数值为：" + parameter.ToString());
                    return Guid.Empty;
                }
                else
                {
                    //[11]添加逻辑状态
                    //int? result = addLogicState(pid, instance.InstanceId, parameter.businessParameter.startDepartment, parameter.businessParameter.startDuty, parameter.businessParameter.startUser, "启动", "");
                    //if (result != null)
                    //{
                    //    MyLog.writeError("createWorkflow方法调用addLogicState方法出错，addLogicState返回值为:" + result.Value.ToString());
                    //    return Guid.Empty;
                    //}


                    //[10]
                    if (parameter.childWorkflowParameter != null)
                    {
                        if (parameter.childWorkflowParameter.regress)
                        {
                            WF_ChildRegress cr = new WF_ChildRegress();
                            cr.masterInstanceID = parameter.childWorkflowParameter.masterInstanceID;
                            cr.instanceID = instance.InstanceId;
                            cr.regressGroup = parameter.childWorkflowParameter.regressGroup;
                            cr.runState = "wait";
                            wfDB.WF_ChildRegress.InsertOnSubmit(cr);
                            try
                            {
                                wfDB.SubmitChanges();
                            }
                            catch (System.Exception ex)
                            {
                                MyLog.writeError(ex.Message);
                            }
                        }
                    }

                    //-----------------------

                    var dfids = wfDB.FM_Form.Where(p => p.businessID == parameter.businessParameter.businessID);
                    foreach (var dfid in dfids)
                    {
                        if (dfid != null)
                        {
                            var df = wfDB.FM_Item.Where(p => p.formID == dfid.formID && p.instanceID == System.Guid.Empty);
                            foreach (var tp in df)
                            {
                                tp.instanceID = instance.InstanceId;
                            }

                            wfDB.SubmitChanges();
                        }
                    }
                    //

                    return instance.InstanceId;
                }
                #endregion [9][return instance.InstanceId]
            }

        }

        //[6.3	业务提交]
        public int? businessSubmit(string pid, SubmitResult submitResult)
        {

            //[0]
            System.Threading.Thread.Sleep(1000);

            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                if(submitResult.nextStateUserNo=="none")
                {
                    submitResult.nextStateUserNo = "";
                }


                //[1]
                if ((submitResult == null) || (submitResult.instanceID == Guid.Empty)
                    || submitResult.stateInstanceID == Guid.Empty || string.IsNullOrEmpty(submitResult.submitUser)
                    || string.IsNullOrEmpty(submitResult.submitDepartment) || string.IsNullOrEmpty(submitResult.submitDuty)
                    || (submitResult.submitTime == null) || string.IsNullOrEmpty(submitResult.submitMode)
                    || string.IsNullOrEmpty(submitResult.triggerType))
                {
                    return 1;
                }

                //[2]
                var stateInstance = wfDB.WF_InstanceState_V.SingleOrDefault(p => p.stateInstanceID == submitResult.stateInstanceID && p.runState == "wait");
                if (stateInstance == null || stateInstance.transactOption.IndexOf(submitResult.submitResult) < 0)
                    return 2;

                //[3]
                List<string> submitModeTemp = new List<string> { "个人", "部门", "职能", "部门职能", "system" };
                if (!submitModeTemp.Exists(delegate(string s) { return s == submitResult.submitMode; }))
                    return 3;

                //[4]

                //[5]
                if (string.IsNullOrEmpty(submitResult.submitDescription))
                    submitResult.submitDescription = "";

                //[6]
                if (string.IsNullOrEmpty(submitResult.nextStateUserNo))
                    submitResult.nextStateUserNo = "";

                //[7]
              
                string dataFormString = null;
                if (submitResult.dataForm != null)
                {
                    if(submitResult.dataForm.childWorkflowTab!=null)
                    {
                       
                        foreach(DataForm.childWorkflowTabRow cRow in submitResult.dataForm.childWorkflowTab.Rows)
                        {
                            if(cRow.IsinstanceIDNull())
                            {
                                cRow.instanceID = Guid.Empty;
                            }
                        }
                    }

                    dataFormString = this.convertDataSetToString(submitResult.dataForm);
                }

                // [7.2]

                if (wfDB.WF_Instance.Single(p => p.instanceID == submitResult.instanceID).isFreeze != 0)
                {
                    return 100;
                }
                                
                //[8]
                this.externalEvent.submitResult(submitResult.instanceID,
                                                submitResult.stateInstanceID,
                                                submitResult.submitResult,
                                                submitResult.submitUser,
                                                submitResult.submitDepartment,
                                                submitResult.submitDuty,
                                                submitResult.submitMode,
                                                submitResult.submitDescription,
                                                submitResult.triggerType,
                                                submitResult.nextStateUserNo,
                                                dataFormString,
                                                submitResult.nextStateTimelimit,
                                                submitResult.nextStateInceptDept,
                                                submitResult.nextStateInceptDuty
                                                );
                return null;
            }
        }

        //[6.4 得到流程结构]
        public WF_Structure getProcessStructure(string pid, Guid instanceID)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (instanceID == null || instanceID == Guid.Empty)
                {
                    return null;
                }

                //[2]
                if (wfDB.WF_Instance.Count(p => p.instanceID == instanceID) == 0)
                {
                    return null;
                }

                //[3]
                if (wfDB.WF_Instance.Count(p => p.instanceID == instanceID) == 1)
                {
                    var instanceInfo = wfDB.WF_Instance.Single(p => p.instanceID == instanceID);
                    //[4]
                    return getWFStructure(pid, instanceInfo.templateID, instanceInfo.templateEdition);
                }
                else
                {
                    return null;
                }
            }
        }

        //[6.5	得到流程运行信息]
        public InstanceInfo getProcessRunInfo(string pid, Guid instanceID)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (instanceID == null || instanceID == Guid.Empty)
                {
                    return null;
                }

                InstanceInfo instanceInfo = new InstanceInfo();

                //[2]
                if (wfDB.WF_Instance_V.Count(p => p.instanceID == instanceID) == 1)
                {
                    var instance = wfDB.WF_Instance_V.SingleOrDefault(p => p.instanceID == instanceID);
                    instanceInfo.instance = instance;
                }

                //[3]
                if (wfDB.WF_InstanceState_V.Count(p => p.instanceID == instanceID && p.runState == "end") != 0)
                {
                    var historyState = wfDB.WF_InstanceState_V.Where(p => p.instanceID == instanceID && p.runState == "end");
                    instanceInfo.historyState = historyState.ToList();
                }

                //[4]
                if (wfDB.WF_InstanceState_V.Count(p => p.instanceID == instanceID && p.runState == "wait") != 0)
                {
                    var currentState = wfDB.WF_InstanceState_V.Where(p => p.instanceID == instanceID && p.runState == "wait");
                    instanceInfo.currentState = currentState.ToList();
                }

                return instanceInfo;
            }

        }

        //X[6.6	更新超时信息]
        public int? refurbishTimelimit(string pid)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                wfDB.refurbishTimelimit();
                return null;
            }
        }

        //X[6.7	超时操作]
        public int? timelimitTransact(string pid)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                var v = wfDB.WF_InstanceState_V.Where(p => p.transactTimelimit < 0 && p.transactOvertimeOperate != "" && p.runState == "wait").ToList();
                foreach (WF_InstanceState_V wf_instanceState_V in v)
                {
                    SubmitResult submitResult = new SubmitResult();
                    submitResult.submitResult = wf_instanceState_V.transactOvertimeOperate;
                    submitResult.instanceID = wf_instanceState_V.instanceID;
                    submitResult.stateInstanceID = wf_instanceState_V.stateInstanceID;
                    submitResult.submitUser = "system";
                    submitResult.submitDepartment = "system";
                    submitResult.submitDuty = "system";
                    submitResult.submitTime = DateTime.Now;
                    submitResult.submitMode = "system";
                    submitResult.triggerType = "超时操作";
                    businessSubmit("", submitResult);
                }
                return null;
            }
        }

        //[6.8	调整流程]
        public int? regulateProcess(string pid, WF_Instance wf_instance)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                //基本信息
                if (string.IsNullOrEmpty(wf_instance.templateID) ||
                    string.IsNullOrEmpty(wf_instance.templateName) ||
                    string.IsNullOrEmpty(wf_instance.templateEdition) ||
                    wf_instance.templateDescription == null ||
                    wf_instance.expandData == null ||
                    wf_instance.templateType == null)
                    return 1;

                ////	表单配置		　
                if (wf_instance.startWindow == null ||
                   wf_instance.dataFormList == null ||
                   wf_instance.startDataForm == null)
                    return 1;

                ////	权限信息	
                if (wf_instance.manageDepartment == null ||
                    wf_instance.manageDuty == null ||
                    wf_instance.manageUser == null ||
                    wf_instance.seeDepartment == null ||
                    wf_instance.seeDuty == null ||
                    wf_instance.seeUser == null ||
                    wf_instance.startUserPower == null ||
                    wf_instance.powerID == null)
                    return 1;

                ////	时限		
                if (wf_instance.overtimeOperate == null)
                    return 1;

                ////	业务信息(启动时)		

                if (
                   string.IsNullOrEmpty(wf_instance.startUser) ||
                   string.IsNullOrEmpty(wf_instance.startDepartment) ||
                   string.IsNullOrEmpty(wf_instance.startDuty) ||
                   wf_instance.businessType == null ||
                   wf_instance.businessID == null ||
                   wf_instance.businessName == null ||                             //businessType,businessID,businessName 可以为""表示可以跑空流程
                   wf_instance.masterBusinessID == null ||
                   wf_instance.businessDescription == null ||
                   wf_instance.urgency == null ||
                   wf_instance.secrecy == null ||
                   wf_instance.startTime == null)
                    return 1;

                ////	子流程		
                if (wf_instance.regressGroup == null ||
                    wf_instance.masterInstanceID == null)
                    return 1;

                ////	数据中转		　
                if (wf_instance.instanceID == null)
                    return 1;

                ////	调试测试		　

                ////	引擎控制		
                if (wf_instance.runState == null ||
                    wf_instance.completeTime == null
                    )
                {
                    return 1;
                }

                //[2]
                WF_Instance wf_instanceFromDB = wfDB.WF_Instance.SingleOrDefault(p => p.instanceID == wf_instance.instanceID);
                if (wf_instanceFromDB != null)
                {
                    Guid g = wf_instanceFromDB.ID;
                    wf_instanceFromDB = wf_instance;
                    wf_instanceFromDB.ID = g;
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    return null;
                }
                else
                {
                    return 2;
                }
            }
        }

        //[6.9	调整状态]
        public int? regulateState(string pid, WF_InstanceState wf_instanceState)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                ////	基本信息	
                if (string.IsNullOrEmpty(wf_instanceState.stateID) ||
                    string.IsNullOrEmpty(wf_instanceState.stateName) ||
                    string.IsNullOrEmpty(wf_instanceState.transactType) ||
                    wf_instanceState.stateDescription == null ||
                    wf_instanceState.powerID == null ||
                    wf_instanceState.expandData == null ||
                    wf_instanceState.createTime == null)
                    return 1;

                ////	表单配置	
                if (
                    wf_instanceState.startWindow == null ||
                    wf_instanceState.dataFormType == null ||
                    wf_instanceState.dataExpression == null
                    )
                    return 1;

                ////	办理权限	

                if (
                    wf_instanceState.transactUser == null ||
                    wf_instanceState.transactPower == null ||
                    wf_instanceState.transactOvertimeOperate == null ||
                    wf_instanceState.transactOption == null ||
                    wf_instanceState.transactSeeForm == null ||
                    wf_instanceState.transactWriteForm == null ||
                    wf_instanceState.transactBegintime == null
                    )
                    return 1;


                ////	接件权限	
                if (
                    wf_instanceState.inceptDepartment == null ||
                    wf_instanceState.inceptDuty == null ||
                    wf_instanceState.inceptPower == null ||
                    wf_instanceState.inceptOvertimeOperate == null
                    )
                    return 1;

                ////	分配权限	
                if (
                    wf_instanceState.assignDepartment == null ||
                    wf_instanceState.assignDuty == null ||
                    wf_instanceState.assignUser == null ||
                    wf_instanceState.assignPower == null ||
                    wf_instanceState.assignOvertimeOperate == null
                    )
                    return 1;

                ////	管理权限		　
                if (
                    wf_instanceState.manageDepartment == null ||
                    wf_instanceState.manageDuty == null ||
                    wf_instanceState.manageUser == null ||
                    wf_instanceState.managePower == null
                    )
                    return 1;

                ////	查看权限		
                if (
                    wf_instanceState.seeDepartment == null ||
                    wf_instanceState.seeDuty == null ||
                    wf_instanceState.seeUser == null ||
                    wf_instanceState.seePower == null
                    )
                    return 1;

                ////	动态域		
                if (
                    wf_instanceState.dynamicDepartment == null ||
                    wf_instanceState.dynamicDuty == null ||
                    wf_instanceState.dynamicUser == null ||
                    wf_instanceState.dynamicPower == null ||
                    wf_instanceState.dynamicType == null
                    )
                    return 1;

                ////	提交上下文		
                if (
                    wf_instanceState.submitPower == null ||
                    wf_instanceState.previousStateInstanceID == null
                    )
                    return 1;

                ////	提交		　
                if (
                    string.IsNullOrEmpty(wf_instanceState.submitResult) ||
                    string.IsNullOrEmpty(wf_instanceState.submitUser) ||
                    string.IsNullOrEmpty(wf_instanceState.submitDepartment) ||
                    string.IsNullOrEmpty(wf_instanceState.submitDuty) ||
                    string.IsNullOrEmpty(wf_instanceState.submitMode) ||
                    string.IsNullOrEmpty(wf_instanceState.triggerType) ||
                    wf_instanceState.submitTime == null ||
                    wf_instanceState.submitDescription == null ||
                    wf_instanceState.nextStateUser == null ||
                    wf_instanceState.dataForm == null
                    )
                    return 1;

                ////	数据中转	
                if (
                    wf_instanceState.stateInstanceID == null
                    )
                    return 1;

                ////	调试测试	
                if (
                    wf_instanceState.debuger == null
                    )
                    return 1;

                ////	引擎控制		
                if (
                    string.IsNullOrEmpty(wf_instanceState.runState) ||
                    wf_instanceState.completeTime == null
                    )
                    return 1;


                //[2]
                WF_InstanceState wf_instanceStateFromDB = wfDB.WF_InstanceState.SingleOrDefault(p => p.instanceID == wf_instanceState.instanceID
                                                                                                     && p.stateInstanceID == wf_instanceState.stateInstanceID);
                if (wf_instanceStateFromDB != null)
                {
                    int g = wf_instanceStateFromDB.autoid;
                    wf_instanceStateFromDB = wf_instanceState;
                    wf_instanceStateFromDB.autoid = g;
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    return null;
                }
                else
                {
                    return 2;
                }
            }
        }

        //[6.10	得到状态列表]
        public List<string> getStateList(string pid, Guid instanceID)
        {
            List<string> states = new List<string>();

            //[1]
            List<Guid> workflowInMemory = new List<Guid>();
            foreach (var workflowInstance in runtime.GetLoadedWorkflows().ToList())
            {
                workflowInMemory.Add(workflowInstance.InstanceId);
            }

            //[2]
            List<Guid> workflowInDB = new List<Guid>();
            foreach (var workflowInDBDescription in persistence.GetAllWorkflows().ToList())
            {
                workflowInDB.Add(workflowInDBDescription.WorkflowInstanceId);
            }

            //[3]
            var worflows = workflowInMemory.Union(workflowInDB).ToList();
            if (worflows.Exists(delegate(Guid i) { return i.Equals(instanceID); }))
            {
                StateMachineWorkflowInstance SMinstance = new StateMachineWorkflowInstance(runtime, instanceID);
                foreach (System.Workflow.Activities.StateActivity temp in SMinstance.States)
                {
                    if (!string.IsNullOrEmpty(temp.Name))
                        states.Add(temp.Name);
                }
            }

            return states;
        }

        //[6.11	状态强行跳转]
        public int? gotoState(string pid, Guid instanceID, string stateName, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (wfDB.WF_Instance_V.Count(p => p.instanceID == instanceID && p.templateType == "状态机") != 1)
                {
                    return 1;
                }

                //[2]
                if (wfDB.WF_Instance_V.Count(p => p.instanceID == instanceID && p.runState == "wait") != 1)
                {
                    return 2;
                }

                //[3]
                var v = getStateList(pid, instanceID);
                if (!(v.Count > 0 && v.Exists(delegate(string t) { return t == stateName; })))
                {
                    return 3;
                }

                //[4]
                StateMachineWorkflowInstance SMinstance = new StateMachineWorkflowInstance(runtime, instanceID);
                if (SMinstance.CurrentStateName == stateName)
                    return 4;

                //[5]
                int? addLogicStateReturn;
                DateTime stateCloseTime = DateTime.Now;
                addLogicStateReturn = addLogicState(pid, instanceID, operateDepartmentNo, operateDutyNo, operateUserNo, "跳转", description);
                if (addLogicStateReturn == null)
                {
                    //[6]
                    WF_InstanceState wf_InstanceState = wfDB.WF_InstanceState.SingleOrDefault(p => p.instanceID == instanceID && p.runState == "wait");
                    if (wf_InstanceState != null)
                    {
                        wf_InstanceState.runState = "end";
                        wf_InstanceState.completeTime = stateCloseTime;
                        try
                        {
                            wfDB.SubmitChanges();
                        }
                        catch (System.Exception ex)
                        {
                            MyLog.writeError(ex.Message);
                        }
                    }
                    SMinstance.SetState(stateName);
                    return null;
                }
                else
                {
                    MyLog.writeError("gotoState方法调用addLogicState方法出错，addLogicState返回值为:" + addLogicStateReturn.ToString());
                    return 5;
                }
            }

        }

        //[6.12	设置状态办理人]
        public int? setStateTransactUser(string pid, Guid instanceID, Guid stateInstanceID, string transactUser, string type, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (wfDB.WF_InstanceState_V.Count(p => p.instanceID == instanceID && p.stateInstanceID == stateInstanceID && p.runState == "wait") != 1)
                {
                    return 1;
                }

                //[2]
                WF_InstanceState_V wf_InstanceState_V = wfDB.WF_InstanceState_V.SingleOrDefault(p => p.stateInstanceID == stateInstanceID);

                switch (type)
                {
                    case "接件":
                        if (!string.IsNullOrEmpty(transactUser) && string.IsNullOrEmpty(wf_InstanceState_V.transactUser))
                        { }
                        else
                        { return 2; };
                        break;
                    case "退回到组":
                        if (string.IsNullOrEmpty(transactUser) && !string.IsNullOrEmpty(wf_InstanceState_V.transactUser))
                        { }
                        else
                        { return 2; };
                        break;
                    case "分配":
                        if (!string.IsNullOrEmpty(transactUser) && string.IsNullOrEmpty(wf_InstanceState_V.transactUser))
                        { }
                        else
                        { return 2; };
                        break;
                    case "拒绝分配":
                        if (string.IsNullOrEmpty(transactUser) && !string.IsNullOrEmpty(wf_InstanceState_V.transactUser))
                        { }
                        else
                        { return 2; };
                        break;
                    case "授权他人":
                        if (!string.IsNullOrEmpty(transactUser))
                        { }
                        else
                        { return 2; };
                        break;
                    case "取回授权":
                        if (!string.IsNullOrEmpty(transactUser) && !string.IsNullOrEmpty(wf_InstanceState_V.transactUser))
                        { }
                        else
                        { return 2; };
                        break;
                    case "取消办理人":
                        if (transactUser=="")
                        { }
                        else
                        { return 2; };
                        break;
                    default:
                        { return 2; };
                }
                //[3]
                int? addLogicStateReturn;
                addLogicStateReturn = addLogicState(pid, instanceID, operateDepartmentNo, operateDutyNo, operateUserNo, type, description);
                if (addLogicStateReturn == null)
                {
                    //[4]
                    WF_InstanceState wf_InstanceState = wfDB.WF_InstanceState.SingleOrDefault(p => p.stateInstanceID == stateInstanceID);
                    wf_InstanceState.transactUser = transactUser;
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    return null;
                }
                else
                {
                    MyLog.writeError("setStateTransactUser方法调用addLogicState方法出错，addLogicState返回值为:" + addLogicStateReturn.ToString());
                    return 3;
                }
            }

        }

        //[6.13	状态延期]
        public int? statePostpone(string pid, Guid instanceID, Guid stateInstanceID, int postponeValue, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                WF_InstanceState wf_InstanceState = wfDB.WF_InstanceState.SingleOrDefault(p => p.instanceID == instanceID &&
                                                                                             p.stateInstanceID == stateInstanceID &&
                                                                                             p.runState == "wait");
                if (wf_InstanceState != null)
                {
                    wf_InstanceState.transactTimelimit = wf_InstanceState.transactTimelimit + postponeValue;
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    int? addLogicStateReturn = addLogicState(pid, instanceID, operateDepartmentNo, operateDutyNo, operateUserNo, "状态延期", description);
                    if (addLogicStateReturn != null)
                    {
                        MyLog.writeError("statePostpone方法调用addLogicState方法出错，addLogicState返回值为:" + addLogicStateReturn.ToString());
                        return 2;
                    }
                    else
                        return null;
                }
                else
                    return 1;
            }

        }

        //[6.14	流程冻结]
        public int? processFreeze(string pid, Guid instanceID, int freeze, string operateDepartmentNo, string operateDutyNo, string operateUserNo, string description)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                WF_Instance wf_Instance = wfDB.WF_Instance.SingleOrDefault(p => p.instanceID == instanceID &&
                                                                                p.runState == "wait");
                if (wf_Instance != null)
                {
                    //[判断freeze]
                    if(wf_Instance.isFreeze==freeze)
                    {
                        return 1;
                    }
                    wf_Instance.isFreeze = freeze;
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    int? addLogicStateReturn = 0;
                    if (freeze == 1)
                        addLogicStateReturn = addLogicState(pid, instanceID, operateDepartmentNo, operateDutyNo, operateUserNo, "流程冻结", description);
                    if (freeze == 0)
                        addLogicStateReturn = addLogicState(pid, instanceID, operateDepartmentNo, operateDutyNo, operateUserNo, "流程解冻", description);
                    if (addLogicStateReturn != null)
                    {
                        MyLog.writeError("processFreeze方法调用addLogicState方法出错，addLogicState返回值为:" + addLogicStateReturn.ToString());
                        return 2;
                    }
                    else return null;

                }
                else return 1;
            }
        }

        //[6.15	得到流程树]
        public InstanceTree getProcessTree(string pid, Guid instanceID)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                InstanceTree instanceTree = new InstanceTree();

                //current
                instanceTree.current = new InstanceInfo();
                instanceTree.current.currentState = wfDB.WF_InstanceState_V.Where(p => p.instanceID == instanceID).ToList();
                instanceTree.current.instance = wfDB.WF_Instance_V.SingleOrDefault(p => p.instanceID == instanceID);
                instanceTree.current.historyState = null;

                //parent
                instanceTree.parent = new InstanceInfo();
                if (instanceTree.current.instance != null)
                {
                    instanceTree.parent.currentState = wfDB.WF_InstanceState_V.Where(p => p.instanceID == instanceTree.current.instance.masterInstanceID).ToList();
                    instanceTree.parent.instance = wfDB.WF_Instance_V.SingleOrDefault(p => p.instanceID == instanceTree.current.instance.masterInstanceID);
                }
                else
                {
                    instanceTree.parent.currentState = wfDB.WF_InstanceState_V.Where(p => false).ToList();
                    instanceTree.parent.instance = wfDB.WF_Instance_V.SingleOrDefault(p => false);
                }
                instanceTree.parent.historyState = null;

                //childList
                var children = wfDB.WF_Instance_V.Where(p => p.masterInstanceID == instanceID);
                instanceTree.childList = new List<InstanceInfo>();
                foreach (WF_Instance_V single in children)
                {
                    InstanceInfo singleInstanceInfo = new InstanceInfo();
                    singleInstanceInfo.currentState = wfDB.WF_InstanceState_V.Where(p => p.instanceID == single.instanceID).ToList();
                    singleInstanceInfo.instance = wfDB.WF_Instance_V.SingleOrDefault(p => p.instanceID == single.instanceID);
                    singleInstanceInfo.historyState = null;
                    instanceTree.childList.Add(singleInstanceInfo);
                }
                return instanceTree;
            }


        }
                
        //[6.16 把DataSet 转化为 字符串]        
        private string convertDataSetToString(DataSet xmlDS)
        {
            MemoryStream stream = null;
            XmlTextWriter writer = null;

            try
            {
                stream = new MemoryStream();
                //从stream装载到XmlTextReader

                writer = new XmlTextWriter(stream, Encoding.UTF8);

                //用WriteXml方法写入文件.

                xmlDS.WriteXml(writer);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);

                UTF8Encoding utf8 = new UTF8Encoding();
                return utf8.GetString(arr).Trim();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }

        }
    }
}

